package com.example.jdbc.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


@Configuration
@MapperScan(basePackages = {"com.example.jdbc.bean.UserMapper"},sqlSessionFactoryRef = "sqlSessionFactory")
public class MybatisDbAConfig {
    @Autowired
    @Qualifier("datasource")
    private DataSource ds;
   @Bean
    public SqlSessionFactory sqlSessionFactory() throws  Exception{
       SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
       factoryBean.setDataSource(ds);
       return factoryBean.getObject();
   }
   @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws  Exception{
       //使用上面配置的Factory
       SqlSessionTemplate template=new SqlSessionTemplate(sqlSessionFactory());
       return  template;

   }
}
